package com.donn.securitycontrolplatform.utils;

import com.donn.securitycontrolplatform.emum.RESULT_CODE;
import com.donn.securitycontrolplatform.expection.BusinessException;
import com.donn.securitycontrolplatform.personinfo.entity.PersonInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Base64;

public class FileUtil {


    /**
     * 文件转base64
     *
     * @param filePath
     * @return
     */
    public static String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 将文件输入流转为base64
     */
    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = in.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }


    /**
     * 通过图片src下载图片
     * 并保存到本地路径
     *
     * @param urlString
     * @param filename
     * @param savePath
     * @throws Exception
     */
    public static void download(String urlString, String filename, String savePath, Integer imgId) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5 * 1000);
        // 输入流
        InputStream is = con.getInputStream();
        String base64FromInputStream = getBase64FromInputStream(is);
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        // 获取图片的扩展名
        String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
        // 新的图片文件名 = 编号 +"."图片扩展名
        String newFileName = imgId + "." + extensionName;
        OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }


    /**
     * 上传文件
     *
     * @param file
     * @param filePath
     * @return
     * @throws BusinessException
     */
    public static String updateFile(MultipartFile file, String filePath) throws BusinessException {
        File file1 = new File(filePath);
        Path fileStorageLocation = file1.toPath();
        Path storagePath = fileStorageLocation.toAbsolutePath().normalize();
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        Path targetLocation = storagePath.resolve(fileName);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            //返回文件路径
            return PersonInfo.PERSON_IMG_CHILD_PATH + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(RESULT_CODE.FILE_IO_EXCEPTION);
        }


    }


}
